package com.busi.framework.base.db;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.sql.DataSource;

import org.jdom.Document;
import org.jdom.Element;
import org.jdom.input.SAXBuilder;
import org.logicalcobwebs.proxool.configuration.PropertyConfigurator;

import com.busi.framework.base.CC;
import com.busi.system.password.PasswordUtil;

public class JdbcConnection {
	private static Connection con = null;
	
	public static Connection getInstance1(){
		if(con == null){
			con = getConnection();
		}
		return con;
	}
	
	private static Connection getConnection(){
		Map map = parseDbXml();
		
		//String url = "jdbc:oracle:thin:@192.168.0.94:1521:orcl";
		//String url = "jdbc:oracle:thin:@127.0.0.1:1521:xe";
		String url = PasswordUtil.getInstance().decryption((String)map.get("driver-url"));
		String username = PasswordUtil.getInstance().decryption((String)map.get("user"));
		String password = PasswordUtil.getInstance().decryption((String)map.get("password"));
		
		try{
			Class.forName((String)map.get("driver-class"));
			con = DriverManager.getConnection(url , username , password);
		}catch(Exception e){
			e.printStackTrace();
		}
		return con;
		
	}
	

	
	
	private static Map parseDbXml(){
		
		Map map = new HashMap();
		
		String xmlPath = CC.REAL_PATH + "/WEB-INF/proxool.xml";
		//String xmlPath = "E:\\hhdc\\hdjs\\web\\WebContent\\WEB-INF\\proxool.xml";
		
		SAXBuilder builder = new SAXBuilder(false);
		try{
			Document doc = builder.build(xmlPath);
			Element root= doc.getRootElement();
			List listProxool = root.getChildren("proxool");
			Element proxool = (Element)listProxool.get(0);
			map.put("driver-url", proxool.getChildText("driver-url"));
			map.put("driver-class", proxool.getChildText("driver-class"));
			
			Element driverProp = proxool.getChild("driver-properties");
			List listProp = driverProp.getChildren();
			
			for(int i = 0 ; i < listProp.size() ; i ++ ){
				Element prop = (Element)listProp.get(i);
				String attributeValue = prop.getAttributeValue("name");
				
				if(attributeValue.equals("user")){
					map.put("user", prop.getAttributeValue("value"));
				}
				if(attributeValue.equals("password")){
					map.put("password", prop.getAttributeValue("value"));
				}
			}
		}catch(Exception e){
			e.printStackTrace();
		}
		
		return map;
	}
	
	
	
}
